import modules from './modules'
import Vue from 'vue'
import Router from '@/js_sdk/uni-simple-router/index.js'
import { getToken } from '@/utils/auth'
import config from '../config.js'

Vue.use(Router)

//初始化
const router = new Router({
	encodeURI:false,  
  routes: [...modules]//路由表
});

// 首页页面
const homePage = "/pages/index"

// 登录页面
const loginPage = config.appInfo.app_type?'/pages/loginSSO': '/pages/login'

const whiteList = ['/pages/register', '/pages/common/webview/index','/pages/loginAuto','/pages/loginSSO','/pages/login'] //,

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	if(getToken()){
		if (to.path === loginPage || to.path === '/') {
				next({ path: homePage })
		}else{
			if(from.path === loginPage || from.path === '/'){	
				const redirect = decodeURIComponent(from.query.redirect || to.path)
				const query = from.query.query || {}
				if (to.path === redirect) {
					next()
				} else {
					// 跳转到目的路由
					next({ path: redirect,query:query })
				}
			}else{
				next()
			}
		}
	}else{
		if (whiteList.indexOf(to.path) !== -1) {
		  next()
		}else {
		  next({ path: loginPage, query: { redirect: to.path,query:to.query }})
		}
	}
})

// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log("afterEach")
})

export default router;